<script setup lang="ts">
import type { VisitorApi } from '#/api';

import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { message } from 'ant-design-vue';

import {
  getTalentDictApi,
  getTalentListApi,
  updateTalentFavoriteApi,
} from '#/api';

interface VisitorInfo {
  id: string;
  name: string;
  sexText: string;
  phone: string;
  email: string;
  professionText: string;
  cityText: string;
  expertise: string[];
  skills: string[];
  experienceYears: number;
  statusText: string;
  collected: number;
  avatar?: string;
  summary?: string;
  enterpriseText?: string;
}

defineOptions({ name: 'VisitorSearch' });

// 响应式数据
const loading = ref(false);
const searchKeyword = ref('');
const searchType = ref<'不限' | '姓名' | '技能' | '职业'>('不限');

// 筛选条件
const filters = reactive({
  profession: '',
  expertise: '',
  skills: '',
  experience: '不限',
  gender: '',
  status: '',
});

const dicts = reactive({
  sex: [] as VisitorApi.DictItem[],
  jobPost: [] as VisitorApi.DictItem[],
  expertise: [] as VisitorApi.DictItem[],
  skillTag: [] as VisitorApi.DictItem[],
  talentStatus: [] as VisitorApi.DictItem[],
});

const professionOptions = computed(() => [
  { value: '', text: '不限' },
  ...dicts.jobPost.map((item) => ({ value: item.value, text: item.text })),
]);

const expertiseOptions = computed(() => [
  { value: '', text: '不限' },
  ...dicts.expertise.map((item) => ({ value: item.value, text: item.text })),
]);
const skillOptions = computed(() => [
  { value: '', text: '不限' },
  ...dicts.skillTag.map((item) => ({ value: item.value, text: item.text })),
]);
const experienceOptions = [
  '不限',
  '应届',
  '1年',
  '1-3年',
  '3-5年',
  '5-10年',
  '10年以上',
  '自定义',
];
const genderOptions = computed(() => [
  { value: '', text: '不限' },
  ...dicts.sex.map((item) => ({ value: item.value, text: item.text })),
]);
const statusOptions = computed(() => [
  { value: '', text: '不限' },
  ...dicts.talentStatus.map((item) => ({ value: item.value, text: item.text })),
  { value: 'favorite', text: '收藏' },
]);

const router = useRouter();

// 搜索结果数据
const searchResults = ref<VisitorInfo[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const statusClassMap: Record<string, string> = {
  空闲: 'bg-green-100 text-green-800',
  测试中: 'bg-blue-100 text-blue-800',
  外派中: 'bg-orange-100 text-orange-800',
  完成: 'bg-gray-100 text-gray-800',
};

const isFavoriteFilter = computed(() => filters.status === 'favorite');

function parseToList(value?: null | string) {
  if (!value) return [];
  return value
    .split(/[,|;、\s]+/)
    .map((item) => item.trim())
    .filter(Boolean);
}

async function fetchDictionaries() {
  try {
    const result = await getTalentDictApi();
    dicts.sex = result.sex ?? [];
    dicts.jobPost = result.gtms_job_post ?? [];
    dicts.expertise = result.gtms_expertise_field ?? [];
    dicts.skillTag = result.gtms_skill_tag ?? [];
    dicts.talentStatus = result.gtms_talent_status ?? [];
  } catch (error) {
    console.error('获取字典数据失败:', error);
  }
}

// 获取游人列表
async function fetchVisitorList() {
  loading.value = true;
  try {
    const payload: VisitorApi.TalentListParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value,
      profession: filters.profession ? [filters.profession] : [],
      expertiseField: filters.expertise ? [filters.expertise] : [],
      skillTags: filters.skills ? [filters.skills] : [],
      // experienceYearsStart: 0,
      // experienceYearsEnd: 0,
      sex: filters.gender,
      status: isFavoriteFilter.value ? '' : filters.status,
      isFavorite: isFavoriteFilter.value ? 1 : 0,
      queryAll: 1,
    };

    if (searchType.value !== '不限' && searchKeyword.value) {
      payload.keyword = searchKeyword.value;
    }

    const result = await getTalentListApi(payload);

    pagination.total = result?.total ?? 0;
    pagination.pageSize = payload.pageSize;
    pagination.current = result?.current || payload.pageNo;

    const records = result?.records ?? [];
    searchResults.value = records.map((item) => ({
      id: item.id,
      name: item.realName,
      sexText: item.sex_dictText || item.sex || '-',
      phone: item.phone,
      email: item.email,
      professionText: item.profession_dictText || item.profession || '-',
      cityText: item.city_dictText || item.city || '-',
      expertise: parseToList(
        item.expertiseField_dictText || item.expertiseField,
      ),
      skills: parseToList(item.skillTags_dictText || item.skillTags),
      experienceYears: item.experienceYears,
      statusText: item.status_dictText || item.status || '-',
      collected: item.collected,
      avatar: item.avator,
      summary: item.summary,
      enterpriseText: item.enterprise_dictText || item.enterprise || '-',
    }));
  } catch (error) {
    console.error('获取游人列表失败:', error);
    message.error('获取游人列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  pagination.current = 1;
  fetchVisitorList();
}

// 切换收藏状态
async function toggleCollect(visitor: VisitorInfo) {
  const target = visitor.collected === 1 ? 0 : 1;
  try {
    await updateTalentFavoriteApi({
      talentId: visitor.id,
      isFavorite: target as 0 | 1,
    });
    visitor.collected = target;
    message.success(target === 1 ? '已收藏' : '已取消收藏');

    if (isFavoriteFilter.value && target === 0) {
      fetchVisitorList();
    }
  } catch (error) {
    console.error('更新收藏状态失败:', error);
    message.error('更新收藏状态失败，请稍后重试');
  }
}

// 查看游人信息
function viewVisitorInfo(visitor: VisitorInfo) {
  router.push({
    name: 'VisitorDetail',
    params: { id: visitor.id },
  });
}

// 分页变化
function handlePageChange(page: number) {
  pagination.current = page;
  fetchVisitorList();
}

// 重置筛选条件
function resetFilters() {
  filters.profession = '';
  filters.expertise = '';
  filters.skills = '';
  filters.experience = '不限';
  filters.gender = '';
  filters.status = '';
  handleSearch();
}

onMounted(async () => {
  await fetchDictionaries();
  fetchVisitorList();
});
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 搜索和筛选区域 -->
    <div class="border-b border-gray-200 bg-white px-6 py-6">
      <!-- 搜索栏 -->
      <div class="mb-6 flex items-center space-x-4">
        <div class="flex items-center space-x-2">
          <select
            v-model="searchType"
            class="rounded-md border border-gray-300 px-3 py-2 text-sm"
          >
            <option value="不限">不限</option>
            <option value="姓名">姓名</option>
            <option value="职业">职业</option>
            <option value="技能">技能</option>
          </select>
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="罗小黑"
            class="w-64 rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-transparent focus:outline-none focus:ring-2 focus:ring-amber-500"
            @keyup.enter="handleSearch"
          />
        </div>
        <button
          @click="handleSearch"
          class="rounded-md bg-amber-500 px-6 py-2 font-medium text-white transition-colors hover:bg-amber-600"
        >
          搜索
        </button>
      </div>

      <!-- 筛选条件 -->
      <div class="space-y-4">
        <!-- 游人职业 -->
        <div>
          <label class="mb-2 block text-sm font-medium text-gray-700"
            >游人职业</label
          >
          <div class="flex flex-wrap gap-2">
            <button
              v-for="option in professionOptions"
              :key="option.value"
              class="rounded-full px-3 py-1 text-sm font-medium transition-colors"
              :class="[
                filters.profession === option.value
                  ? 'bg-yellow-400 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
              ]"
              @click="
                filters.profession = option.value;
                handleSearch();
              "
            >
              {{ option.text }}
            </button>
          </div>
        </div>

        <!-- 擅长领域 -->
        <div>
          <label class="mb-2 block text-sm font-medium text-gray-700"
            >擅长领域</label
          >
          <div class="flex flex-wrap gap-2">
            <button
              v-for="option in expertiseOptions"
              :key="option.value"
              class="rounded-full px-3 py-1 text-sm font-medium transition-colors"
              :class="[
                filters.expertise === option.value
                  ? 'bg-yellow-400 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
              ]"
              @click="
                filters.expertise = option.value;
                handleSearch();
              "
            >
              {{ option.text }}
            </button>
          </div>
        </div>

        <!-- 技能标签 -->
        <div>
          <label class="mb-2 block text-sm font-medium text-gray-700"
            >技能标签</label
          >
          <div class="flex flex-wrap gap-2">
            <button
              v-for="option in skillOptions"
              :key="option.value"
              class="rounded-full px-3 py-1 text-sm font-medium transition-colors"
              :class="[
                filters.skills === option.value
                  ? 'bg-yellow-400 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
              ]"
              @click="
                filters.skills = option.value;
                handleSearch();
              "
            >
              {{ option.text }}
            </button>
          </div>
        </div>

        <!-- 从业年限 -->
        <div>
          <label class="mb-2 block text-sm font-medium text-gray-700"
            >从业年限</label
          >
          <div class="flex flex-wrap gap-2">
            <button
              v-for="option in experienceOptions"
              :key="option"
              class="rounded-full px-3 py-1 text-sm font-medium transition-colors"
              :class="[
                filters.experience === option
                  ? 'bg-yellow-400 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
              ]"
              @click="
                filters.experience = option;
                handleSearch();
              "
            >
              {{ option }}
            </button>
          </div>
        </div>

        <!-- 其他筛选 -->
        <div class="flex items-center space-x-4">
          <div>
            <label class="mb-1 block text-sm font-medium text-gray-700"
              >性别</label
            >
            <select
              v-model="filters.gender"
              @change="handleSearch"
              class="rounded-md border border-gray-300 px-3 py-1 text-sm"
            >
              <option
                v-for="option in genderOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.text }}
              </option>
            </select>
          </div>
          <div>
            <label class="mb-1 block text-sm font-medium text-gray-700"
              >状态</label
            >
            <select
              v-model="filters.status"
              @change="handleSearch"
              class="rounded-md border border-gray-300 px-3 py-1 text-sm"
            >
              <option
                v-for="option in statusOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.text }}
              </option>
            </select>
          </div>
          <button
            @click="resetFilters"
            class="rounded-md bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-200"
          >
            重置筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 搜索结果区域 -->
    <div class="px-6 py-6">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-12">
        <div
          class="h-8 w-8 animate-spin rounded-full border-b-2 border-amber-500"
        ></div>
      </div>

      <!-- 搜索结果 -->
      <div v-else-if="searchResults.length > 0" class="space-y-4">
        <div
          v-for="visitor in searchResults"
          :key="visitor.id"
          class="cursor-pointer rounded-lg border border-gray-200 bg-white p-6 shadow-sm transition-shadow hover:shadow-md"
          @click="viewVisitorInfo(visitor)"
        >
          <div class="flex items-start space-x-4">
            <!-- 头像 -->
            <div
              class="flex h-16 w-16 items-center justify-center overflow-hidden rounded-full bg-gradient-to-r from-blue-400 to-purple-500 text-lg font-bold text-white"
            >
              <img
                v-if="visitor.avatar"
                :src="visitor.avatar"
                alt="avatar"
                class="h-full w-full object-cover"
              />
              <span v-else>{{ visitor.name.charAt(0) }}</span>
            </div>

            <!-- 基本信息 -->
            <div class="flex-1">
              <div class="mb-2 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-900">
                  {{ visitor.name }}
                </h3>
                <div class="flex items-center space-x-2">
                  <span
                    class="rounded-full px-2 py-1 text-xs font-medium"
                    :class="[
                      statusClassMap[visitor.statusText] ??
                        'bg-gray-100 text-gray-600',
                    ]"
                  >
                    {{ visitor.statusText }}
                  </span>
                  <button
                    class="rounded-full px-2 py-1 text-xs font-medium transition-colors"
                    :class="[
                      visitor.collected === 1
                        ? 'bg-yellow-400 text-white'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200',
                    ]"
                    @click.stop="toggleCollect(visitor)"
                  >
                    {{ visitor.collected === 1 ? '已收藏' : '未收藏' }}
                  </button>
                </div>
              </div>

              <div class="mb-2 text-sm text-gray-600">
                {{ visitor.professionText }} ·
                {{
                  visitor.experienceYears ? `${visitor.experienceYears}年` : '-'
                }}
                · {{ visitor.cityText }}
              </div>

              <div class="mb-3 text-sm text-gray-600">
                擅长领域: {{ visitor.expertise.join(' ') || '-' }}
              </div>

              <div class="mb-4 text-sm text-gray-700">
                {{ visitor.summary || '暂无简介' }}
              </div>

              <!-- 技能标签 -->
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="skill in visitor.skills"
                  :key="skill"
                  class="rounded-full bg-green-100 px-2 py-1 text-xs font-medium text-green-800"
                >
                  {{ skill }}
                </span>
                <span
                  v-if="visitor.skills.length === 0"
                  class="text-xs text-gray-400"
                  >暂无技能标签</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="py-12 text-center">
        <div class="text-gray-500">
          <svg
            class="mx-auto h-12 w-12 text-gray-400"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
            />
          </svg>
          <h3 class="mt-2 text-sm font-medium text-gray-900">暂无搜索结果</h3>
          <p class="mt-1 text-sm text-gray-500">请尝试调整搜索条件</p>
        </div>
      </div>

      <!-- 分页 -->
      <div
        v-if="!loading && searchResults.length > 0"
        class="mt-6 flex justify-center"
      >
        <div class="flex items-center space-x-2">
          <button
            :disabled="pagination.current <= 1"
            class="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
            @click="handlePageChange(pagination.current - 1)"
          >
            上一页
          </button>

          <button
            v-for="page in Math.min(
              5,
              Math.ceil(pagination.total / pagination.pageSize),
            )"
            :key="page"
            class="rounded-md border px-3 py-2 text-sm font-medium"
            :class="[
              page === pagination.current
                ? 'border-amber-500 bg-amber-500 text-white'
                : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50',
            ]"
            @click="handlePageChange(page)"
          >
            {{ page }}
          </button>

          <button
            :disabled="
              pagination.current >=
              Math.ceil(pagination.total / pagination.pageSize)
            "
            class="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
            @click="handlePageChange(pagination.current + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
